function[]=ksbivardens(X,f,akce)
%KSBIVARDENS  kernel bivariate density estimation
%
%  ksbivardens(X,f)
%  GUI for Kernel Density Estimation
%  X - random sample
%  f - original density (if known)
%
% (C) Jan Kolacek, Masaryk University (Czech Republic)

w=which('ksbivardens.m');
w(end-13:end)=[];
addpath(w);
addpath([w,'/regress']);
addpath([w,'/quality']);
addpath([w,'/distrib']);
addpath([w,'/bivardens']);
addpath([w,'/dens']);
addpath([w,'/dens/base']);
addpath([w,'/dens/functions']);

if nargin<1
    br=get(0,'DefaultFigureColor');
    %%v4colset;
    save v.mat br;
    
    callbackStr=['set(gcf,''CloseRequestFcn'',''closereq'');',...
        'load v.mat;if br~=[0 0 0] v5colset;end;', ...
        'clear;load puvprom;close(findobj(0,''Tag'',''kclos''));',...
        'delete v.mat;delete puvprom.mat;delete(gcf);'];
    
    crStr= 'save puvprom;';
    
    figure( ...
        'Visible','on', ...
        'Name','DATA LOADING', ...
        'CloseRequestFcn',callbackStr,...
        'Units','Normalized',...
        'CreateFcn',crStr,...
        'Tag','defprom',...
        'NumberTitle','off');
    
    uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'FontUnits','normalized',...
        'Position',[.4,.85,.2,.1], ...
        'BackgroundColor',[0.8 0.8 0.8], ...
        'ForegroundColor',[1 0 0], ...
        'FontSize',0.5,...
        'String','Load Data');
    
    uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'FontUnits','normalized',...
        'Position',[.1,.75,.3,.1], ...
        'HorizontalAlignment','left',...
        'BackgroundColor',[0.8 0.8 0.8], ...
        'ForegroundColor',[0 0 0], ...
        'FontSize',0.4,...
        'String','Select a file to load:');
    
    prom=char(who('-file','puvprom.mat'));
    S=whos('-file','puvprom.mat');
    idtxt=zeros(length(S),1);
    iddbl=zeros(length(S),1);
    for i=1:length(S)
        idtxt(i)=strcmp(S(i).class,'char');
        iddbl(i)=strcmp(S(i).class,'double');
    end
    promtxt=prom(logical(idtxt),:);
    promdbl=prom(logical(iddbl),:);
    rozhtxt='on';
    
    if size(prom,1)<1
        rozh='off';
    else
        if size(prom,1)==1
            evalin('base','f_def_for_me=[];');
        end
        rozh='on';
    end
    
    if size(promdbl,1)<1
        promdbl=char('[]','[]');
    end
    if size(promtxt,1)<1
        promtxt=char('[]');
        rozhtxt='off';
    end
    
    % The BROWSE button
    call='uiopen(''LOAD'');prom=char(who);GG=get(gcf,''userdata'');G=GG.hndlList;';
    call1='if size(prom,1)>2 set([G(1),G(3)],''String'',prom);set([G(1),G(2),G(3),G(4)],''Enable'',''on'');end;';
    call2='ind=get(G(1),''Value'');prom=get(G(1),''String'');X_def_for_me=eval(prom(ind,:));';
    call3='ind=get(G(3),''Value'');prom=get(G(3),''String'');f_def_for_me=eval(prom(ind,:));';
    uicontrol( ...
        'Style','push', ...
        'Units','normalized', ...
        'FontUnits','normalized',...
        'Position',[0.4,.8,.1,0.07], ...
        'String','Browse', ...
        'Callback',[call,call1,call2,call3]);
    
    uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'FontUnits','normalized',...
        'Position',[.1,.675,.3,.1], ...
        'BackgroundColor',[0.8 0.8 0.8], ...
        'ForegroundColor',[0 0 0], ...
        'FontSize',0.4,...
        'String','OR');
    
    uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'FontUnits','normalized',...
        'Position',[.1,.6,.3,.1], ...
        'HorizontalAlignment','left',...
        'BackgroundColor',[0.8 0.8 0.8], ...
        'ForegroundColor',[0 0 0], ...
        'FontSize',0.4,...
        'String','Make a simulation:');
    
    % The SIMULATION button
    uicontrol( ...
        'Style','push', ...
        'Units','normalized', ...
        'FontUnits','normalized',...
        'Position',[0.4,.65,.1,0.07], ...
        'String','Simulation', ...
        'Callback','simulbivar');
    
    uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'FontUnits','normalized',...
        'Position',[.1,.5,.6,.1], ...
        'HorizontalAlignment','left',...
        'BackgroundColor',[0.8 0.8 0.8], ...
        'ForegroundColor',[0 0 0], ...
        'FontSize',0.4,...
        'String','Define the name of the sample (X):');
    
    xHndl=uicontrol( ...
        'Style','popup', ...
        'Enable',rozh,...
        'Units','normalized', ...
        'FontUnits','normalized',...
        'Position',[.7,.55,.1,.04], ...
        'String',promdbl, ...
        'FontSize',0.7,...
        'Callback',['GG=get(gcf,''userdata'');G=GG.hndlList;set(G(4),''enable'',''on'');ind=get(G(1),''Value'');prom=get(G(1),''String'');X_def_for_me=eval(prom(ind,:));f_def_for_me=[];']);
    
    uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'FontUnits','normalized',...
        'Position',[.1,.3,.6,.1], ...
        'HorizontalAlignment','left',...
        'BackgroundColor',[0.8 0.8 0.8], ...
        'ForegroundColor',[0 0 0], ...
        'FontSize',0.4,...
        'String','Write true density function (if known):');
    
    tHndl=uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'FontUnits','normalized',...
        'Position',[.65,.35,.15,.05], ...
        'String','', ...
        'HorizontalAlignment','left',...
        'Callback','GG=get(gcf,''userdata'');G=GG.hndlList;f_def_for_me=get(G(2),''String'');');
    %        'CreateFcn',['m_def=',promtxt(1,:),';'],...
    
    uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'FontUnits','normalized',...
        'Position',[.2,.22,.6,.1], ...
        'HorizontalAlignment','left',...
        'BackgroundColor',[0.8 0.8 0.8], ...
        'ForegroundColor',[0 0 0], ...
        'FontSize',0.4,...
        'String','or load the name from a variable: ');
    
    call1='GG=get(gcf,''userdata'');G=GG.hndlList;ind=get(G(3),''Value'');prom=get(G(3),''String'');';
    call2='f_def_for_me=eval(prom(ind,:));set(G(2),''String'',f_def_for_me);';
    rHndl=uicontrol( ...
        'Style','popup', ...
        'Enable',rozhtxt,...
        'Units','normalized', ...
        'FontUnits','normalized',...
        'Position',[.7,.28,.1,.04], ...
        'String',promtxt, ...
        'Value',1,...
        'Callback',[call1,call2]);
    
    % The CONTINUE button
    call='GG=get(gcf,''userdata'');save pom.mat X_def_for_me f_def_for_me GG;close(gcf);';
    call1='load pom;if ischar(f_def_for_me) ksbivardens(X_def_for_me,f_def_for_me); else ksbivardens(X_def_for_me); end;';
    cHndl=uicontrol( ...
        'Style','push', ...
        'Enable','off',...
        'Units','normalized', ...
        'FontUnits','normalized',...
        'Position',[0.8,.1,.1,0.07], ...
        'String','Continue', ...
        'Callback',[call,call1]);
    
    
    G.hndlList=[xHndl,tHndl,rHndl,cHndl];
    G.w=[];
    G.mu=[];
    G.sigma=[];
    set(gcf,'UserData',G);
    %set(gcf,'Position',[0 0.0347 1.0000 0.9190]);
    set(gcf,'Position',[0.1059 0.1655 0.7700 0.6898]);
    
else
    if nargin <= 2
        akce='inic';
    end
    if (nargin >= 2)&&(~isempty(f))
        rozhzpus='on';
    else
        rozhzpus='off';
        f=[];
    end
    switch akce
        case 'inic'
            br=get(0,'DefaultFigureColor');
            %%v4colset;
            
            callbackStr=['set(gcf,''CloseRequestFcn'',''closereq'');',...
                'load v.mat;if br~=[0 0 0] v5colset;end;', ...
                'clear;load puvprom;close(findobj(0,''Tag'',''kclos''));',...
                'close(findobj(''tag'',''data_contour''));close(findobj(''tag'',''data_dens''));',...
                'close(findobj(''tag'',''est_contour''));close(findobj(''tag'',''est_dens''));',...
                'delete v.mat;delete puvprom.mat;delete(gcf);'];
            
            crStr= 'save puvprom;';
            % unts = get(0,'Units');
            % set(0,'Units','Normalized');
            % scrsz = get(0,'ScreenSize');
            % set(0,'Units',unts);
            %
            if exist('pom.mat','file')
                load pom.mat;
                delete pom.mat;
            else
                GG.w=[];
                GG.mu=[];
                GG.sigma=[];
            end
           
            C=figure( ...
                'Visible','on', ...
                'Name','KERNEL SMOOTHING', ...
                'CloseRequestFcn',callbackStr,...
                'CreateFcn',crStr,...
                'NumberTitle','off',...
                'Units','Normalized',...
                'UserData',GG);
            
            save v.mat C br;
            axes( ...
                'Units','normalized', ...
                'Position',[0.08 0.08 0.75 0.87]);
            
            % The CONSOLE frame
            uicontrol( ...
                'Style','frame', ...
                'Units','normalized', ...
                'FontUnits','normalized',...
                'Position',[0.86,0,.15,1], ...
                'BackgroundColor',[0.50 0.50 0.50]);
            
            top=.85;
            fsz=0.31;  %FontSize
            % The Zadani button
            call='G=get(gcf,''UserData'');C=G.simfig;t=findobj(0,''name'',''EDIT'');';...
                call1=['if isempty(t) prosvitbivar(C);zadanibivar;else set(t,''Visible'',''off'');', ...
                'set(t,''Visible'',''on'');end;'];...
                uicontrol( ...
                'Style','push', ...
                'Units','normalized', ...
                'FontUnits','normalized',...
                'Position',[0.88,top,.1,0.1], ...
                'String','Setting', ...
                'Callback',[call,call1]);
            
            % The Estimate button
            
            c1 = 'G=get(gcf,''UserData'');ksbivardens(G.X,G.dens,''estimate'');';
            estHndl=uicontrol( ...
                'Style','push', ...
                'Units','normalized', ...
                'FontUnits','normalized',...
                'Position',[0.88,top-.15,.1,.1], ...
                'String','Estimate', ...
                'Enable','off',...
                'Callback',c1);
            
            
            uicontrol( ...
                'Style','text', ...
                'Units','normalized', ...
                'FontUnits','normalized',...
                'Position',[0.88,top-.3,.1,0.07], ...
                'HorizontalAlignment','left',...
                'BackgroundColor',[0.5 0.5 0.5], ...
                'ForegroundColor',[0 0 0], ...
                'String','Type of view:');
            
            c1='G=get(gcf,''UserData'');X=G.X;f=G.dens;ksbivardens(X,f,''dens'');';
            rad1Hndl=uicontrol( ...
                'Style','radiobutton', ...
                'Enable',rozhzpus,...
                'Units','normalized', ...
                'FontUnits','normalized',...
                'Position',[.88,top-.35,.1,.05], ...
                'HorizontalAlignment','left',...
                'BackgroundColor',[0.5 0.5 0.5], ...
                'Callback',c1,...
                'String','Density');
            
            c1='G=get(gcf,''UserData'');X=G.X;f=G.dens;ksbivardens(X,f,''data'');';
            rad2Hndl=uicontrol( ...
                'Style','radiobutton', ...
                'Units','normalized', ...
                'FontUnits','normalized',...
                'Position',[.88,top-.4,.1,.05], ...
                'HorizontalAlignment','left',...
                'BackgroundColor',[0.5 0.5 0.5], ...
                'Value',1,...
                'Callback',c1,...
                'String','Data');
            
            c1='G=get(gcf,''UserData'');X_def_for_me=G.X;f_def_for_me=G.dens;';
            c2='ksbivardens(X_def_for_me,f_def_for_me,''pridejuber'');';
            origHndl=uicontrol( ...
                'Style','checkbox', ...
                'Units','normalized', ...
                'FontUnits','normalized',...
                'Position',[.88,top-.5,.1,.05], ...
                'HorizontalAlignment','left',...
                'BackgroundColor',[0.5 0.5 0.5], ...
                'Value',1,...
                'Callback',[c1,c2],...
                'String','Original');
            
            % The SAVE text
            uicontrol( ...
                'Style','text', ...
                'Units','normalized', ...
                'FontUnits','normalized',...
                'Position',[.88,.25,.1,.04], ...
                'BackgroundColor',[0.5 0.5 0.5], ...
                'String','Save Data:');
            
            % The VAR button
            call=['G=get(gcf,''UserData'');checkLabels = {''Save observations to variable named:'','...
                '''Save density estimates to variable named:'',',...
                '''Save design points to variable named:'',',...
                '''Save bandwidth matrix to variable named:''};',...
                'varNames = {''X'',''f_est'',''xx'',''H''};',...
                'items = {G.X,G.f_est,G.xx,G.H};clear G;',...
                'save ppp;save pp checkLabels varNames items;clear;load pp;delete pp.mat;',...
                '[hdialog,ok_pressed]=export2wsdlg(checkLabels,varNames,items,''Save Data'');'...
                'if ok_pressed G=get(gcf,''userdata'');set(G.hndlList(6),''enable'',''on'');',...
                'clear G hdialog ok_pressed checkLabels varNames items;varNames=who;',...
                'save v varNames -append;save(''puvprom'',varNames{:},''-append'');end;load ppp;delete ppp.mat'];
            labelStr='var';
            varHndl=uicontrol( ...
                'Style','push', ...
                'Enable','off',...
                'Units','normalized', ...
                'FontUnits','normalized',...
                'Position',[0.88,.2,.05,0.05], ...
                'String',labelStr, ...
                'Callback',call);
            
            % The FILE button
            labelStr='file';
            call=['load v; uisave(varNames,''data_ks'')'];
            fileHndl=uicontrol( ...
                'Style','push', ...
                'Enable','off',...
                'Units','normalized', ...
                'FontUnits','normalized',...
                'Position',[0.93,.2,.05,0.05], ...
                'String',labelStr, ...
                'Callback',call);
            
            % The CLOSE button
            labelStr='Close';
            uicontrol( ...
                'Style','push', ...
                'Units','normalized', ...
                'FontUnits','normalized',...
                'Position',[0.88,.08,.1,.1], ...
                'String',labelStr, ...
                'Callback',callbackStr);
            
            % The Print button
            labelStr='P';
            call1=['G=get(gcf,''userdata'');fig=figure(''Units'',''normalized'',',...
                '''NumberTitle'',''off'',''Name'',''DATA PLOT'',''Position'',[0.1059 0.1655 0.7700 0.6898]);',...
                'figure(G.simfig);copyobj(get(gcf,''CurrentAxes''),fig);figure(fig);',...
                'set(gca,''Position'',[0.08 0.08 0.84 0.84]);'];
            call2=['hL=G.hndlList;clbr=get(hL(2),''Value'');',...
                'if clbr==1, colorbar; end;set(gca,''DataAspectRatioMode'',''manual'');'];
            
            uicontrol( ...
                'Style','push', ...
                'Units','normalized', ...
                'FontUnits','normalized',...
                'Position',[0.001,.96,.03,0.035], ...
                'String',labelStr, ...
                'Callback',[call1,call2]);
            
            G=get(gcf,'UserData');
            G.hndlList=[rad1Hndl,rad2Hndl,...
                estHndl,origHndl,...
                varHndl,fileHndl];
            G.dens=f;
            G.X=X;
            G.simfig=C;
            G.H=wand(X);
            
            for i=1:2
                h1_max=std(X(i,:));
                xxspec=[linspace(min(X(i,:))-h1_max,max(X(i,:))+h1_max)];
                nX=min(xxspec);mX=max(xxspec);
                xx(i,:)=linspace(nX,mX,50);
            end
            G.xx=xx;

            set(gcf,'UserData',G);
            %set(C,'Position',[0 0.0347 1.0000 0.9190]);
            set(C,'Position',[0.1059 0.1655 0.7700 0.6898]);
            %set(C,'Position',[1 1 .97 .9].*scrsz+[.01 .012 0 0]);
            set(origHndl,'visible',rozhzpus);
            ksbivardens(X,f,'first');

        case 'first'
            G=get(gcf,'UserData');
            xx=G.xx;
            [x,y]=meshgrid(xx(1,:),xx(2,:));
            
            figure('visible','off','tag','data_contour');
            axa=axes('Units','normalized', ...
                'Position',[0.08 0.08 0.75 0.87]);
            plot(X(1,:),X(2,:),'x');
            if ~isempty(f)
            set(axa,'Position',[0.08 0.08 0.85 0.87]);
                fx=eval(vectorize(f));
                hold on;contour(x,y,fx,':');
                colorbar;
                hold off;
            end
            figure('visible','off','tag','data_dens');
            axes('Units','normalized', ...
                'Position',[0.08 0.08 0.75 0.87]);
            if ~isempty(f)
                fx=eval(vectorize(f));
                mesh(x,y,fx);
            end
            g=findobj('tag','data_contour');
            ez2=get(g,'CurrentAxes');
            figure(G.simfig);
            delete(gca);
            copyobj(ez2,gcf);
            if ~isempty(f)
            hold on
            colorbar;
            hold off
            end
            
        case 'data'
            G=get(gcf,'UserData');
            hL=G.hndlList;
            set(hL(1),'value',0);            
            set(hL(2),'value',1);
            fir=findobj('tag','est_contour');
            if isempty(fir)
                g=findobj('tag','data_contour');
            else
                g=fir;
            end
            ez2=get(g,'CurrentAxes');
            figure(G.simfig);
            delete(gca);
            copyobj(ez2,gcf);
            hold on
            colorbar;
            hold off
            set(hL(4),'Value',1);
            if ~isempty(f)
            set(hL(4),'visible','on');
            end
            fir=findobj('tag','est_contour');
            if ~isempty(fir)
                figure(G.simfig);
                hold on
                colorbar;
                hold off
                set(hL(4),'Value',0);
            end
        case 'dens'
            G=get(gcf,'UserData');
            hL=G.hndlList;
            set(hL(1),'value',1);            
            set(hL(2),'value',0);
            set(hL(4),'visible','off');
            fir=findobj('tag','est_dens');
            if isempty(fir)
                g=findobj('tag','data_dens');
            else
                g=fir;
            end
            ez2=get(g,'CurrentAxes');
            figure(G.simfig);
            delete(gca);
            copyobj(ez2,gcf);
        case 'estimate'
            G=get(gcf,'UserData');
            close(findobj('tag','est_contour'));
            close(findobj('tag','est_dens'));
            figure('visible','off','tag','est_dens');
            axes('Units','normalized', ...
                'Position',[0.08 0.08 0.75 0.87]);
            [f,x,Z]=ksmultidens(X,G.n,G.k,G.m,G.H,G.xx,G.styl);
            G.f_est=f;
            set(G.simfig,'UserData',G);
            xx=x(1,:);
            yy=x(2,:);
            [XX,YY]=meshgrid(xx,yy);
            mesh(XX,YY,Z);
            figure('visible','off','tag','est_contour');
            axes('Units','normalized', ...
                'Position',[0.08 0.08 0.75 0.87]);
            contour(XX,YY,Z);hold on;
            plot(X(1,:),X(2,:),'x');
            hL=G.hndlList;
            val=get(hL(2),'Value');
            if val==1
                g=findobj('tag','est_contour');
                ez2=get(g,'CurrentAxes');
                figure(G.simfig);
                delete(gca);
                copyobj(ez2,gcf);
                hold on
                colorbar;
                hold off
            else
                g=findobj('tag','est_dens');
                ez2=get(g,'CurrentAxes');
                figure(G.simfig);
                delete(gca);
                copyobj(ez2,gcf);
            end
            set(hL(4),'Value',0);
            set(hL(1),'Enable','on');
            set(hL(5),'Enable','on');
        case 'pridejuber'
            G=get(gcf,'UserData');
            xx=G.xx;
            hL=G.hndlList;
            val=get(hL(4),'Value');
            fir=findobj('tag','est_contour');
            fird=findobj('tag','data_contour');
            if isempty(fir)
                if val==0
                    figure(G.simfig);
                    delete(gca);
                    axes('Units','normalized', ...
                        'Position',[0.08 0.08 0.75 0.87]);
                    plot(X(1,:),X(2,:),'x');
                else
                    ez2=get(fird,'CurrentAxes');
                    figure(G.simfig);
                    delete(gca);
                    copyobj(ez2,gcf);
                    hold on
                    colorbar;
                    hold off
                end
            else
                if val==0
                    ez2=get(fir,'CurrentAxes');
                    figure(G.simfig);
                    delete(gca);
                    copyobj(ez2,gcf);
                    hold on
                    colorbar;
                    hold off
                else
                    [x,y]=meshgrid(xx(1,:),xx(2,:));
                    fx=eval(vectorize(f));
                    hold on;contour(x,y,fx,':');
                    colorbar;
                    hold off;
                end
            end
    end
    
end
